<%-- 
    Document   : index
    Created on : 01.03.2014, 9:54:11
    Author     : romanupgrate
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
    double version = Math.random();
    request.setAttribute("version", version);
%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Альфа версия</title>
        <link href="css/main.css?v=${version}" rel="stylesheet">
        <script src="js/jquery-2.1.0.min.js" type="text/javascript"></script>
        <script src="js/jquery.json-2.3.js"></script>
        <script type="text/javascript" src="js/util.js?v=${version}"></script>
        <script type="text/javascript" src="js/full_screen_api.js?v=${version}"></script>
        <script type="text/javascript" src="js/workPictures.js?v=${version}"></script>
        <script type="text/javascript" src="js/utilFunction.js?v=${version}"></script>
        <script type="text/javascript" src="js/interface.js?v=${version}"></script>
        <script type="text/javascript" src="js/mouse.event.js?v=${version}"></script>
        <script type="text/javascript" src="js/keysend.js?v=${version}"></script>
        <script type="text/javascript" src="js/draw.js?v=${version}"></script>
        <script>
            var canvas, mapCanvas, hpCanvas;
            var canvasSven;
            var speedMoveCanvas = 20;
            var mapW = 2250, mapH = 2250;
            var heroSize = 250;
            var user_id = ${user.id};//Math.round((Math.random() * 1000));
            var meId;
            var meTeamId;
            var browserDetect;
            var isInitDxDy = false;
            var img_cursor = "cur";
            document.oncontextmenu = function () {
                return false;
            }
            function initCanvasBaseStyle() {
                var fontSize = 12;
                canvas.font = Math.round(fontSize / SCALE) + 'px sans-serif';
                canvas.textBaseline = 'bottom';
                canvas.fillStyle = "rgb(255,255,255)";
                canvas.strokeStyle = "rgb(20,20,20)";
                canvas.lineWidth = 5;
            }
            function draw()
            {
                var str = "";
                var tDU = new Date().getTime();
                var tD = new Date().getTime();
                calcMouse();
                calc(objects);
                newTimeDraw = new Date().getTime();
                canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
                str = str + " c" + Math.round(new Date().getTime() - tDU);
                tDU = new Date().getTime();
                drawMapFromCanvasMap(canvas);
                //drawMapNew(canvas);
                str = str + " m" + Math.round(new Date().getTime() - tDU);

                tDU = new Date().getTime();
                //drawUnitSelected(canvas);
                drawTowers(canvas, objects.towers);
                str = str + " t" + Math.round(new Date().getTime() - tDU);
                tDU = new Date().getTime();
                drawUnits(canvas, objects.heroes);
                str = str + " u" + Math.round(new Date().getTime() - tDU);
                tDU = new Date().getTime();
                drawUnitsHpNew(canvas);
                str = str + " hp" + Math.round(new Date().getTime() - tDU);
                tDU = new Date().getTime();
                canvas.save();
                if (!isFullScreen()) {
                    canvas.scale(SCALE, SCALE);
                }
                drawArrows(canvas, objects.arrows);
                drawEsplosionBloods(canvas, objects.explosionBloods);
                canvas.restore();
                str = str + " a" + Math.round(new Date().getTime() - tDU);
                str = " all=" + Math.round(new Date().getTime() - tD) + " " + str;
                cFPS();
                $("#log").html(str);
            }
            function endPreloadImg() {
                resizeWindow();
                initHpCanvas();
                showGame();
                //initCanvasHeroes(basicHeroList, 0);
            }
            function showGame() {
                ws.init();
                $("#playGame").show();
                initPage("menu");
            }
            window.addEventListener('load', function () {
                canvas = document.getElementById('gameCanvas').getContext("2d");
                mapCanvas = document.getElementById('mapCanvas').getContext("2d");
                hpCanvas = document.getElementById('hpCanvas').getContext("2d");
                preload.push({t: "../maps/img", i: "map_new", e: "jpg"});
                /*for (var n = 1; n <= 3; n++) {
                 for (var k = 1; k <= 3; k++) {
                 preload.push({t: "../maps/img", i: "a_" + n + "_" + k, e: "jpg"});
                 }
                 }*/
                preloadPicture(0);
                $("#gameCanvas").mousemove(mouseMove);
                $("#gameCanvas").mouseover(mouseOver);
                $("#gameCanvas").mouseout(mouseOut);
                $("#gameCanvas").mousedown(mouseDown);
                $("#gameCanvas").mouseup(mouseUp);
                $("#menuPanel").mousemove(mouseMove);
                $("#controlPanel").mousemove(mouseMove);
                $("#controlPanel").mousedown(mouseDown);
                $("#controlPanel").mouseup(mouseUp);
                $(document).bind('keyup', KEY_UP, keyEvent);
                $(document).bind('keydown', KEY_DOWN, keyEvent);
                browserDetect = browserDetectNav();
                //window.addEventListener('resize', resizeWindow, false);
                //window.addEventListener('orientationchange', resizeWindow, false);
                initHeroesList();
            }, false);
            var ws = {
                init: function () {
                    //conn = new WebSocket('ws://localhost:8089/');
                    conn = new WebSocket('ws://31.220.26.30:8089/');
                    conn.onopen = this.onConnected
                    conn.onclose = this.onDisconnected
                    conn.onmessage = this.onMessage
                    this.conn = conn;
                },
                sendMessage: function (message) {
                    this.conn.send(message);
                },
                onConnected: function () {
                    $("#log").html("Подключено");
                    ws.sendMessage("cn" + user_id);
                },
                onDisconnected: function () {
                    $("#log").html("Отключено");
                    if (isPage != "menu") {
                        initPage("menu");
                        GAME = false;
                    }
                    setTimeout(function () {
                        $("#log").html("Подключаемся...");
                        ws.init();
                        ws.sendMessage("cn" + user_id);
                    }, 5000);

                },
                onMessage: function (response) {
                    newTimeServer = new Date().getTime();
                    var delay = newTimeServer - oldTimeServer;
                    oldTimeServer = newTimeServer;
                    mFPS++;
                    var typeMsg = response.data.substring(0, 2);
                    var msg = response.data.substring(2, response.data.length);
                    if (typeMsg === "un") {
                        var tD = new Date().getTime();
                        var data = msg.split("\uE000");
                        meId = data[0].charCodeAt(0);
                        parseHeroes(data[1]);
                        spliceHeroes();
                        if (!isInitDxDy) {
                            goToHero(meId);
                            isInitDxDy = true;
                        }
                        //parseSelected(data[2]);
                        parseArrows(data[3]);
                        spliceArrows();
                        parseTowers(data[4]);
                        spliceTowers();
                        $(".log2").html("time: " + Math.round(new Date().getTime() - tD) + " size:" + response.data.length);
                        if (GAME == false) {
                            initPage("play");
                            GAME = true;
                            animate();
                        }
                    } else if (typeMsg === "in") {//получение статической информации при входе в комнату тут обнулить переменные инциализация.
                        isInitDxDy = false;
                    } else if (typeMsg == "dl") { //удаление юнита со списка
                        var tmp_objects = response.data.substring(2, response.data.length);
                        var dl = tmp_objects.charCodeAt(0);
                        for (var j = 0; j < objects.unitsStaticInfo.length; j++) {
                            if (objects.unitsStaticInfo[j].id == dl) {
                                objects.unitsStaticInfo.splice(j, 1);
                                break;
                            }
                        }
                        resetHeroPanel();
                    } else if (typeMsg == "au") {//статическая информация о юнитах чтоб не передавать каждый тик
                        var tmp_objects = jQuery.parseJSON(response.data.substring(2, response.data.length));
                        for (var j = 0; j < tmp_objects.length; j++) {
                            var flagFind = false;
                            for (var k = 0; k < objects.unitsStaticInfo.length; k++) {
                                if (tmp_objects[j].id == objects.unitsStaticInfo[k].id) {
                                    objects.unitsStaticInfo[k] = tmp_objects[j];
                                    flagFind = true;
                                    break;
                                }
                            }
                            if (!flagFind)
                                objects.unitsStaticInfo.push(tmp_objects[j]);
                        }
                        resetHeroPanel();
                    } else if (typeMsg == "rm") {//Раунд message
                        var tmp_objects = response.data.substring(2, response.data.length);
                        if (tmp_objects == "l") {
                            alert("ПРОИГРАЛИ авто выходод через 5 сек.")
                        } else {
                            alert("ВЫИГРАЛИ авто выходод через 5 сек.")
                        }
                        setTimeout(function () {
                            exitRoom();
                        }, 5000);
                    }
                },
                logMessage: function (message) {
                    $("#log").html(message);
                },
                oldMsg: ""
            }
            function initPage(p) {
                $(".page").hide();
                $("#" + p).show();
            }
            function isPage(p) {
                return $("#" + p).is(':visible');
            }
        </script>
    </head>
    <body id="ultBody">
        <div id="play" class="page">
            <div id="initWindow"></div>
            <canvas id="gameCanvas" width="867" height="620" ></canvas>
            <canvas id="mapCanvas" width="4500" height="4500" style="position: absolute;top: 0;left: 0; display: none;"></canvas>
            <canvas id="hpCanvas" width="60" height="5" style="position: absolute;top: 0;left: 0;display: none;"></canvas>
            <div id="menuPanel">
                <button id="fsbutton" onclick="fullScreen();">Full</button>
                <button id="exitRoom" onclick="exitRoom();">Выход</button>
                <div id="panelHeroes">
                    <div class="winHero" style="background-image: url('img/heroes_pic/sven_full.png');"></div>
                    <div class="winHero"></div>
                    <div class="winHero"></div>
                    <div class="winHero"></div>
                    <div class="winHero"></div>
                    <div class="winTimer">time</div>
                    <div class="winHero"></div>
                    <div class="winHero"></div>
                    <div class="winHero"></div>
                    <div class="winHero"></div>
                    <div class="winHero"></div>
                </div>
            </div>
            <div id="controlPanel">
                <div class="map l"></div>
                <div class="all l">
                    <div class="hero l">
                        <div class="l">
                            <div class="img"></div>
                            <div class="hp">
                                <div class="percent"></div>
                                <div class="value"></div>
                            </div>
                            <div class="mp">
                                <div class="percent"></div>
                                <div class="value"></div>
                            </div>
                        </div>
                        <div class="l" style="text-align: left;">
                            <div class="name">Имя героя</div>
                            <div class="parametrs1 l"></div>
                            <div class="parametrs2 l" style="padding-left: 20px;"></div>
                            <div class="cl"></div>  
                        </div>
                        <div class="cl"></div>  
                    </div>
                </div>
                <div class="skill l log2">Рюкзак</div>
                <div class="cl"></div>                
            </div>
        </div>
        <div id="ultFPS"></div> 
        <div id="log"></div>
        <jsp:include page="/WEB-INF/jsp/menu.jsp" />
    </body>
</html>
